package com.ruoyi.member.controller.app;

import java.util.List;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.member.domain.MemberCollection;
import com.ruoyi.member.domain.Comment;
import com.ruoyi.member.domain.MemberLike;
import com.ruoyi.member.domain.MemberRate;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.member.service.ICollectionService;
import com.ruoyi.member.service.ICommentService;
import com.ruoyi.member.service.IMemberLikeService;
import com.ruoyi.member.service.IMemberRateService;

/**
 * App端会员模块Controller
 *
 * @author ruoyi
 * @date 2025-01-05
 */
@RestController
@RequestMapping("/app/member")
public class MemberAppController extends BaseController
{
    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ICollectionService collectionService;

    @Autowired
    private ICommentService commentService;

    @Autowired
    private IMemberLikeService memberLikeService;

    @Autowired
    private IMemberRateService memberRateService;

    /**
     * 用户登录（手机号登录）
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody SysUser loginRequest)
    {
        // 根据手机号查找用户
        SysUser query = new SysUser();
        query.setPhonenumber(loginRequest.getPhonenumber());
        List<SysUser> list = sysUserService.selectUserList(query);

        if (list == null || list.isEmpty()) {
            return error("用户不存在");
        }

        SysUser user = list.get(0);

        // 验证密码
        if (!SecurityUtils.matchesPassword(loginRequest.getPassword(), user.getPassword())) {
            return error("密码错误");
        }

        // 创建LoginUser对象并生成JWT token
        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(user.getUserId());
        loginUser.setUser(user);

        // 生成token
        String token = tokenService.createToken(loginUser);

        AjaxResult ajax = AjaxResult.success();
        ajax.put(Constants.TOKEN, token);
        ajax.put("user", user);
        return ajax;
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public AjaxResult register(@RequestBody SysUser user)
    {
        // 检查手机号是否已注册
        SysUser query = new SysUser();
        query.setPhonenumber(user.getPhonenumber());
        List<SysUser> list = sysUserService.selectUserList(query);

        if (list != null && !list.isEmpty()) {
            return error("手机号已注册");
        }

        // 创建新用户
        int result = sysUserService.insertUser(user);
        if (result > 0) {
            return success(user);
        }
        return error("注册失败");
    }

    /**
     * 获取当前登录用户信息（从JWT token获取，带Redis缓存）
     */
    @GetMapping("/info")
    public AjaxResult getUserInfo()
    {
        Long userId = SecurityUtils.getUserId();

        // 缓存key
        String cacheKey = "member:userinfo:" + userId;

        // 1. 先从Redis缓存获取
        SysUser cachedUser = redisCache.getCacheObject(cacheKey);
        if (cachedUser != null) {
            return success(cachedUser);
        }

        // 2. 缓存未命中，从数据库查询
        SysUser user = sysUserService.selectUserById(userId);

        // 3. 存入Redis缓存（30分钟过期）
        if (user != null) {
            redisCache.setCacheObject(cacheKey, user, 30, TimeUnit.MINUTES);
        }

        return success(user);
    }

    /**
     * 更新用户信息（更新后清除缓存）
     */
    @PutMapping("/info")
    public AjaxResult updateUserInfo(@RequestBody SysUser user)
    {
        int result = sysUserService.updateUser(user);

        // 更新成功后清除Redis缓存
        if (result > 0) {
            Long userId = SecurityUtils.getUserId();
            String cacheKey = "member:userinfo:" + userId;
            redisCache.deleteObject(cacheKey);
        }

        return toAjax(result);
    }

    // ==================== 收藏相关 ====================

    /**
     * 获取当前用户收藏列表（从JWT token获取userId）
     */
    @GetMapping("/collections")
    public TableDataInfo getCollections()
    {
        startPage();
        Long userId = SecurityUtils.getUserId();
        MemberCollection query = new MemberCollection();
        query.setUserId(userId);
        List<MemberCollection> list = collectionService.selectCollectionList(query);
        return getDataTable(list);
    }

    /**
     * 添加收藏（短视频）
     */
    @PostMapping("/collection")
    public AjaxResult addCollection(@RequestBody MemberCollection collection)
    {
        // 检查是否已收藏
        MemberCollection query = new MemberCollection();
        query.setUserId(collection.getUserId());
        query.setShortId(collection.getShortId());
        List<MemberCollection> list = collectionService.selectCollectionList(query);

        if (list != null && !list.isEmpty()) {
            return error("已收藏");
        }

        return toAjax(collectionService.insertCollection(collection));
    }

    /**
     * 取消收藏
     */
    @DeleteMapping("/collection/{collectionId}")
    public AjaxResult removeCollection(@PathVariable Long collectionId)
    {
        return toAjax(collectionService.deleteCollectionById(collectionId));
    }

    /**
     * 检查是否已收藏（从JWT token获取userId）
     */
    @GetMapping("/collection/check")
    public AjaxResult checkCollection(@RequestParam Integer shortId)
    {
        Long userId = SecurityUtils.getUserId();
        MemberCollection query = new MemberCollection();
        query.setUserId(userId);
        query.setShortId(shortId);
        List<MemberCollection> list = collectionService.selectCollectionList(query);
        return success(list != null && !list.isEmpty());
    }

    // ==================== 评论相关 ====================

    /**
     * 获取视频评论列表（包括弹幕）
     */
    @GetMapping("/comments/video/{videoId}")
    public TableDataInfo getVideoComments(@PathVariable Integer videoId, @RequestParam(required = false) String isDm)
    {
        startPage();
        Comment query = new Comment();
        query.setVideoId(videoId);
        if (isDm != null) {
            query.setIsDm(isDm);
        }
        List<Comment> list = commentService.selectCommentList(query);
        return getDataTable(list);
    }

    /**
     * 获取弹幕列表
     */
    @GetMapping("/danmaku/video/{videoId}")
    public AjaxResult getDanmaku(@PathVariable Integer videoId)
    {
        Comment query = new Comment();
        query.setVideoId(videoId);
        query.setIsDm("1"); // 1=弹幕
        List<Comment> list = commentService.selectCommentList(query);
        return success(list);
    }

    /**
     * 发表评论/弹幕
     */
    @PostMapping("/comment")
    public AjaxResult addComment(@RequestBody Comment comment)
    {
        return toAjax(commentService.insertComment(comment));
    }

    /**
     * 删除评论
     */
    @DeleteMapping("/comment/{commentId}")
    public AjaxResult removeComment(@PathVariable Long commentId)
    {
        return toAjax(commentService.deleteCommentById(commentId));
    }

    // ==================== 点赞相关 ====================

    /**
     * 点赞短视频
     */
    @PostMapping("/like")
    public AjaxResult addLike(@RequestBody MemberLike like)
    {
        // 检查是否已点赞
        MemberLike query = new MemberLike();
        query.setUserId(like.getUserId());
        query.setShortId(like.getShortId());
        List<MemberLike> list = memberLikeService.selectMemberLikeList(query);

        if (list != null && !list.isEmpty()) {
            // 已点赞，则取消点赞
            memberLikeService.cancelLike(like.getUserId(), like.getShortId());
            return success("取消点赞");
        }

        // 添加点赞
        memberLikeService.insertMemberLike(like);
        return success("点赞成功");
    }

    /**
     * 检查是否已点赞（从JWT token获取userId）
     */
    @GetMapping("/like/check")
    public AjaxResult checkLike(@RequestParam Integer shortId)
    {
        Long userId = SecurityUtils.getUserId();
        MemberLike query = new MemberLike();
        query.setUserId(userId);
        query.setShortId(shortId);
        List<MemberLike> list = memberLikeService.selectMemberLikeList(query);
        return success(list != null && !list.isEmpty());
    }

    // ==================== 评分相关 ====================

    /**
     * 对影视评分
     */
    @PostMapping("/rate")
    public AjaxResult addRate(@RequestBody MemberRate rate)
    {
        // 检查是否已评分
        MemberRate query = new MemberRate();
        query.setUserId(rate.getUserId());
        query.setMovieBasicsId(rate.getMovieBasicsId());
        List<MemberRate> list = memberRateService.selectMemberRateList(query);

        if (list != null && !list.isEmpty()) {
            // 已评分，更新评分
            rate.setMemberRateId(list.get(0).getMemberRateId());
            return toAjax(memberRateService.updateMemberRate(rate));
        }

        // 新增评分
        return toAjax(memberRateService.insertMemberRate(rate));
    }

    /**
     * 获取影视的用户评分（从JWT token获取userId）
     */
    @GetMapping("/rate/movie/{movieBasicsId}")
    public AjaxResult getMovieRate(@PathVariable Integer movieBasicsId)
    {
        Long userId = SecurityUtils.getUserId();
        MemberRate query = new MemberRate();
        query.setUserId(userId);
        query.setMovieBasicsId(movieBasicsId);
        List<MemberRate> list = memberRateService.selectMemberRateList(query);

        if (list != null && !list.isEmpty()) {
            return success(list.get(0));
        }
        return success(null);
    }

    /**
     * 获取影视的平均评分
     */
    @GetMapping("/rate/movie/{movieBasicsId}/avg")
    public AjaxResult getMovieAvgRate(@PathVariable Integer movieBasicsId)
    {
        MemberRate query = new MemberRate();
        query.setMovieBasicsId(movieBasicsId);
        List<MemberRate> list = memberRateService.selectMemberRateList(query);

        if (list != null && !list.isEmpty()) {
            double avgRate = list.stream()
                    .mapToInt(MemberRate::getRate)
                    .average()
                    .orElse(0.0);
            return success(AjaxResult.success()
                    .put("avgRate", avgRate)
                    .put("rateCount", list.size()));
        }
        return success(AjaxResult.success()
                .put("avgRate", 0)
                .put("rateCount", 0));
    }
}
